﻿using System.Collections.Generic;
using System.Linq;
using RBOSS.Business.CustomerModule;
using RBOSS.Business.Products;
using RBOSS.Data;

namespace RBOSS.Business.ShoppingCarts
{
    public class ShoppingCartSubsystem : IShoppingCartSubsystem
    {
        private readonly IShoppingCart _shoppingCart;
        private ICustomer _customer;
        RBOSSEntities _dataContext = new RBOSSEntities();

        public ShoppingCartSubsystem()
        {
            _shoppingCart = CustomerSingleton.GetShoppingCart();
            _customer = CustomerSingleton.GetCustomer();
        }

        public void AddItemToCart(IProduct product, int quantity)
        {
            _shoppingCart.AddItemToCart(product, quantity);
        }

        public void RemoveItemFromCart(int productId)
        {
            _shoppingCart.RemoveItemFromCart(productId);
        }

        public void ClearItemFromCart()
        {
            _shoppingCart.ClearItemFromCart();
        }

        public void RetrieveShoppingCart()
        {
            var customerId = _customer.CustomerDetails.CustomerId;
            var shoppintCart = from cart in _dataContext.ShoppingCarts where cart.UserId == customerId select cart;

            _shoppingCart.ClearItemsFromSessionCart();
            foreach (var p in shoppintCart)
            {
                var product = new Products.Product()
                {
                    Qunatity = p.Quantity,
                    CategoryId = p.Product.CategoryId,
                    Description = p.Product.Description,
                    Image = p.Product.Image,
                    Price = p.Product.UnitPrice,
                    ProductId = p.ProductId,
                    ProductName = p.Product.ProductName,
                    VendorId = p.Product.UserId

                };
                _shoppingCart.AddItemToSessionCart(product,p.Quantity);
            }

        }


        public bool HasLogin()
        {
            return _customer.CustomerDetails != null && _customer.CustomerDetails.CustomerId > 0;

        }

        public void SaveCartToDataBase()
        {
            if (HasLogin())
            {
                _shoppingCart.SaveCartToDataBase();
            }
        }

        public List<IProduct> GetProducts()
        {
            return _shoppingCart.GetProducts();
        }

    }
}